﻿using System;
using System.Collections.Generic;
using System.Linq;
using System.Text;
using ClickGame.GUI.Controls;
using Common.Entities;
using Common.Enums;
using Common.Packets;
using Lidgren.Network;
using Microsoft.Xna.Framework;
using Microsoft.Xna.Framework.Content;
using Microsoft.Xna.Framework.Graphics;
using TomShane.Neoforce.Controls;
using Console = TomShane.Neoforce.Controls.Console;
using EventArgs = TomShane.Neoforce.Controls.EventArgs;

namespace ClickGame.Screens
{
    public class GameScreen : Screen
    {
        private Texture2D texture;
        private Game1 _game;
        Random rnd = new Random();

        //private Manager _manager;
        private Window _window;

        private ImageBox _ginger;//картинка пряника
        private ImageBox _gingerMan;//картинка пряничного человечка
        private ImageBox _advancedGingerMan;//картинка улучшенного пряничного человечка
        private ImageBox _glasur;//картинка глазури
        private ImageBox _gingerFlare;//подсветка
        private ImageBox _gingerManFlare;
        private ImageBox _advancedGingerManFlare;
        private ImageBox _glasurFlare;
        private ImageBox _goldenGinger;
        private Panel _leftPanel;
        private Panel _centerPanel;
        private AdvancedStackPanel _rightUpPanel;
        private Console _console;

        private ImageBox _divider;//картинка разделителя

        private Label _stats;//статистика

        //текстуры
        private Texture2D _gingerImg;
        private Texture2D _gingerManImg;
        private Texture2D _advancedGingerManImg;
        private Texture2D _glasurImg;

        private Texture2D _gingerImgGlow;
        private Texture2D _gingerManImgGlow;
        private Texture2D _advancedGingerManImgGlow;
        private Texture2D _glasurImgGlow;
        private Texture2D _flareImg;
        List<Button> _structureButtons = new List<Button>();
        List<ImageButton> _achievementsButtons = new List<ImageButton>();
        List<ImageButton> _upgradeButtons = new List<ImageButton>();
        List<ImageButton> _gainedUpgradeButtons = new List<ImageButton>();
        public EventedList<ConsoleMessage> ChatBuffer = new EventedList<ConsoleMessage>();

        private AdvancedStackPanel _gainedUpgradesPanel;//купленные апгрейды

        private User _user;

        private DateTime _goldenGingerAppeared = DateTime.MinValue;
        //private DateTime _goldenGingerClicked = DateTime.MinValue;

        public User User
        {
            get { return _user; }
            set { _user = value; }
        }

        private float _passedTime = 0.0f;
        private byte _gingerclicks = 0;
        private byte _glasurclicks = 0;
        private byte _gingermanclicks = 0;
        private byte _advgingermanclicks = 0;
        private float _rotationAngle = 0.0f;

        private string _structureToolTip = @"Стоимость в пряниках: {0}
Доход пряников в сек: {1}
Доход пряничных человечков в сек: {2}
Доход глазури в сек: {3}
Доход продвинутых пряничных человечков в сек: {4}
Уже построено: {5}";

        private const int ImgPaddingConst = 175;

        public Dictionary<MessageType, Texture2D> _msgImgs;//массив с иконками сообщений

        private string _statsTemplate = @"Всего пряников: {0}
Пряников в секунду: {1} (Бонус: {2}%)
Пряников за клик: {3}
Всего пряничных человечков: {4}
Пряничных человечков в секунду: {5}
Всего глазури: {6}
Глазури за клик: {7}
Глазури в секунду: {8}
Улучшенных пряничных человечков в секунду: {9}
Всего улучшенных пряничных человечков:  {10}
Текущий уровень: {11}
Опыт: {12}/{13}";

        public GameScreen(Game1 game, User user)
        {
            _game = game;
            _user = user;
            _msgImgs = new Dictionary<MessageType, Texture2D>();
        }
        public override void Draw(GameTime gameTime)
        {


            base.Draw(gameTime);
        }
        public override void Update(GameTime gameTime)
        {
            if (_passedTime >= 1.0f)
            {
                _passedTime = 0.0f;
                NetOutgoingMessage nom = Game1.Client.CreateMessage();
                nom.Write((short)PacketType.Refresh);
                nom.Write(_gingerclicks);
                nom.Write(_glasurclicks);
                nom.Write(_gingermanclicks);
                nom.Write(_advgingermanclicks);
                _gingerclicks = 0;
                _glasurclicks = 0;
                _gingermanclicks = 0;
                _advgingermanclicks = 0;
                RefreshStructureButtons();
                Game1.Client.SendMessage(nom, NetDeliveryMethod.ReliableOrdered);
            }
            _passedTime += (float)gameTime.ElapsedGameTime.TotalSeconds;
            _stats.Text = string.Format(_statsTemplate, _user.Money.ToString("N"), (_user.Income * (decimal)(1.0f + _user.Multiplier)).ToString("N4"), (_user.Multiplier * 100.0f).ToString("N0"), _user.ClickIncome.ToString("N"), _user.GingerMan.ToString("N0"), _user.GingerManIncome.ToString("N"),
    _user.Glasur.ToString("N1"), _user.GlasurClickIncome.ToString("N"), _user.GlasurIncome.ToString("N4"), _user.AdvancedGingerManIncome.ToString("N4"), _user.AdvancedGingerMan.ToString("N0"), _user.Lvl, _user.Exp.ToString("N0"), (100 * (Math.Pow(1.8, (_user.Lvl - 1)))).ToString("N0"));

            _rotationAngle += (float)gameTime.ElapsedGameTime.TotalSeconds / 10f;
            float circle = MathHelper.Pi * 2;
            _rotationAngle = _rotationAngle % circle;

            _gingerFlare.Rotation = _rotationAngle;
            _gingerManFlare.Rotation = _rotationAngle;
            _glasurFlare.Rotation = _rotationAngle;
            _advancedGingerManFlare.Rotation = _rotationAngle;

            if (gameTime.ElapsedGameTime.TotalSeconds > 0 && !_user.Paused)
            {
                _user.Money += (_user.Income * (decimal)gameTime.ElapsedGameTime.TotalSeconds) +
                               ((_user.Income * (decimal)gameTime.ElapsedGameTime.TotalSeconds) *
                                (decimal)_user.Multiplier);
                if (_user.GingerManIncome > 0 && _user.Money >= 1000.0m * (decimal)gameTime.ElapsedGameTime.TotalSeconds)
                {
                    _user.GingerMan += (_user.GingerManIncome * (decimal)gameTime.ElapsedGameTime.TotalSeconds);
                    _user.Money -= 1000.0m * (decimal)gameTime.ElapsedGameTime.TotalSeconds;
                }

                _user.Glasur += (_user.GlasurIncome * (decimal)gameTime.ElapsedGameTime.TotalSeconds);

                if (_user.AdvancedGingerManIncome > 0 && _user.Money >= 10000.0m * (decimal)gameTime.ElapsedGameTime.TotalSeconds && _user.Glasur >= 100.0m * (decimal)gameTime.ElapsedGameTime.TotalSeconds && _user.GingerMan >= 3.0m * (decimal)gameTime.ElapsedGameTime.TotalSeconds)
                {
                    _user.AdvancedGingerMan += (_user.AdvancedGingerManIncome *
                                                (decimal)gameTime.ElapsedGameTime.TotalSeconds);
                    _user.Money -= 10000.0m * (decimal)gameTime.ElapsedGameTime.TotalSeconds;
                    _user.Glasur -= 100.0m * (decimal)gameTime.ElapsedGameTime.TotalSeconds;
                    _user.GingerMan -= 3.0m * (decimal)gameTime.ElapsedGameTime.TotalSeconds;
                }
            }
            if (_user.Money < 1000.0m)
            {
                _gingerMan.Color = Color.Black;
            }
            else
            {
                _gingerMan.Color = Color.White;
            }
            if (_user.GingerMan >= 3 && _user.Glasur >= 1000 && _user.Money >= 10000)
            {
                _advancedGingerMan.Color = Color.White;
            }
            else
            {
                _advancedGingerMan.Color = Color.Black;
            }
            if (_user.GlasurClickIncome > 0)
            {
                _glasur.Color = Color.White;
            }
            else
            {
                _glasur.Color = Color.Black;
            }
            if (_goldenGinger.Visible)
            {
                if (_goldenGingerAppeared.AddSeconds(20) < DateTime.Now)
                {
                    _goldenGinger.Visible = false;//you fucked up the golden ginger :(
                }
            }
            base.Update(gameTime);
        }
        public override void LoadContent(ContentManager content)
        {
            _msgImgs.Add(MessageType.Error, (Texture2D)Game1.Resources.GetResource("Skins\\Default\\Images\\Icon.Error", typeof(Texture2D)));
            _msgImgs.Add(MessageType.Question, (Texture2D)Game1.Resources.GetResource("Skins\\Default\\Images\\Icon.Question", typeof(Texture2D)));
            _msgImgs.Add(MessageType.General, (Texture2D)Game1.Resources.GetResource("Skins\\Default\\Images\\Icon.Information", typeof(Texture2D)));
            _msgImgs.Add(MessageType.Warning, (Texture2D)Game1.Resources.GetResource("Skins\\Default\\Images\\Icon.Warning", typeof(Texture2D)));

            _gingerImg = (Texture2D)Game1.Resources.GetResource("Images/Game/ginger", typeof(Texture2D));
            _gingerManImg = (Texture2D)Game1.Resources.GetResource("Images/Game/gingerman", typeof(Texture2D));
            _advancedGingerManImg = (Texture2D)Game1.Resources.GetResource("Images/Game/advgingerman", typeof(Texture2D));
            _glasurImg = (Texture2D)Game1.Resources.GetResource("Images/Game/glasur", typeof(Texture2D));

            _gingerImgGlow = (Texture2D)Game1.Resources.GetResource("Images/Game/ginger_glow", typeof(Texture2D));
            _gingerManImgGlow = (Texture2D)Game1.Resources.GetResource("Images/Game/gingerman_glow", typeof(Texture2D));
            _advancedGingerManImgGlow = (Texture2D)Game1.Resources.GetResource("Images/Game/advgingerman_glow", typeof(Texture2D));
            _glasurImgGlow = (Texture2D)Game1.Resources.GetResource("Images/Game/glasur_glow", typeof(Texture2D));
            _flareImg = (Texture2D)Game1.Resources.GetResource("Images/Game/shine", typeof(Texture2D));

            _leftPanel = new Panel(_game.Manager);
            _leftPanel.Init();
            _leftPanel.Width = 210;
            _leftPanel.Height = _game.MainWindow.Height - 35;
            _leftPanel.Parent = _game.MainWindow;
            _leftPanel.BevelBorder = BevelBorder.Right;
            _leftPanel.BevelStyle = BevelStyle.Bumped;

            _gingerFlare = new ImageBox(_game.Manager);
            _gingerFlare.Left = 2;
            _gingerFlare.Top = 0;
            _gingerFlare.Image = _flareImg;
            _gingerFlare.Width = 200;
            _gingerFlare.Height = 200;
            _gingerFlare.SizeMode = SizeMode.Stretched;
            _gingerFlare.Parent = _leftPanel;
            _gingerFlare.Origin = new Vector2(_flareImg.Width / 2, _flareImg.Height / 2);
            _gingerFlare.Color = Color.FromNonPremultiplied(255, 255, 255, 128);

            _gingerManFlare = new ImageBox(_game.Manager);
            _gingerManFlare.Left = 2;
            _gingerManFlare.Top = _gingerFlare.Top + ImgPaddingConst;
            _gingerManFlare.Image = _flareImg;
            _gingerManFlare.Width = 200;
            _gingerManFlare.Height = 200;
            _gingerManFlare.SizeMode = SizeMode.Stretched;
            _gingerManFlare.Parent = _leftPanel;
            _gingerManFlare.Origin = new Vector2(_flareImg.Width / 2, _flareImg.Height / 2);
            _gingerManFlare.Color = Color.FromNonPremultiplied(255, 255, 255, 128);

            _glasurFlare = new ImageBox(_game.Manager);
            _glasurFlare.Left = 2;
            _glasurFlare.Top = _gingerManFlare.Top + ImgPaddingConst;
            _glasurFlare.Image = _flareImg;
            _glasurFlare.Width = 200;
            _glasurFlare.Height = 200;
            _glasurFlare.SizeMode = SizeMode.Stretched;
            _glasurFlare.Parent = _leftPanel;
            _glasurFlare.Origin = new Vector2(_flareImg.Width / 2, _flareImg.Height / 2);
            _glasurFlare.Color = Color.FromNonPremultiplied(255, 255, 255, 128);

            _advancedGingerManFlare = new ImageBox(_game.Manager);
            _advancedGingerManFlare.Left = 2;
            _advancedGingerManFlare.Top = _glasurFlare.Top + ImgPaddingConst;
            _advancedGingerManFlare.Image = _flareImg;
            _advancedGingerManFlare.Width = 200;
            _advancedGingerManFlare.Height = 200;
            _advancedGingerManFlare.SizeMode = SizeMode.Stretched;
            _advancedGingerManFlare.Parent = _leftPanel;
            _advancedGingerManFlare.Origin = new Vector2(_flareImg.Width / 2, _flareImg.Height / 2);
            _advancedGingerManFlare.Color = Color.FromNonPremultiplied(255, 255, 255, 128);


            _ginger = new ImageBox(_game.Manager);
            _ginger.Left = 51;
            _ginger.Top = 50;
            _ginger.Image = _gingerImg;
            _ginger.MouseDown += new MouseEventHandler(clickers_MouseDown);
            _ginger.MouseUp += new MouseEventHandler(clickers_MouseUp);
            _ginger.MouseOut += new MouseEventHandler(clickers_MouseOut);
            _ginger.MouseOver += new MouseEventHandler(clickers_MouseOver);
            _ginger.Tag = 0;
            _ginger.Width = 100;
            _ginger.Height = 100;
            _ginger.SizeMode = SizeMode.Stretched;
            _ginger.Parent = _leftPanel;

            _gingerMan = new ImageBox(_game.Manager);
            _gingerMan.Left = 54;
            _gingerMan.Top = _ginger.Top + ImgPaddingConst;
            _gingerMan.Image = _gingerManImg;
            _gingerMan.MouseDown += new MouseEventHandler(clickers_MouseDown);
            _gingerMan.MouseUp += new MouseEventHandler(clickers_MouseUp);
            _gingerMan.MouseOut += new MouseEventHandler(clickers_MouseOut);
            _gingerMan.MouseOver += new MouseEventHandler(clickers_MouseOver);
            _gingerMan.Tag = 1;
            _gingerMan.Width = 100;
            _gingerMan.Height = 100;
            _gingerMan.SizeMode = SizeMode.Stretched;
            _gingerMan.Parent = _leftPanel;

            _glasur = new ImageBox(_game.Manager);
            _glasur.Left = 53;
            _glasur.Top = _gingerMan.Top + ImgPaddingConst;
            _glasur.Image = _glasurImg;
            _glasur.MouseDown += new MouseEventHandler(clickers_MouseDown);
            _glasur.MouseUp += new MouseEventHandler(clickers_MouseUp);
            _glasur.MouseOut += new MouseEventHandler(clickers_MouseOut);
            _glasur.MouseOver += new MouseEventHandler(clickers_MouseOver);
            _glasur.Tag = 2;
            _glasur.Width = 100;
            _glasur.Height = 100;
            _glasur.SizeMode = SizeMode.Stretched;
            _glasur.Parent = _leftPanel;

            _advancedGingerMan = new ImageBox(_game.Manager);
            _advancedGingerMan.Left = 50;
            _advancedGingerMan.Top = _glasur.Top + ImgPaddingConst;
            _advancedGingerMan.Image = _advancedGingerManImg;
            _advancedGingerMan.MouseDown += new MouseEventHandler(clickers_MouseDown);
            _advancedGingerMan.MouseUp += new MouseEventHandler(clickers_MouseUp);
            _advancedGingerMan.MouseOut += new MouseEventHandler(clickers_MouseOut);
            _advancedGingerMan.MouseOver += new MouseEventHandler(clickers_MouseOver);
            _advancedGingerMan.Tag = 3;
            _advancedGingerMan.Width = 100;
            _advancedGingerMan.Height = 100;
            _advancedGingerMan.SizeMode = SizeMode.Stretched;
            _advancedGingerMan.Parent = _leftPanel;

            _ginger.Init();
            _gingerMan.Init();
            _glasur.Init();
            _advancedGingerMan.Init();

            _centerPanel = new Panel(_game.Manager);
            _centerPanel.Init();
            _centerPanel.Left = 210;
            _centerPanel.Width = 500;
            _centerPanel.Height = _game.MainWindow.Height - 35;
            _centerPanel.Parent = _game.MainWindow;
            _centerPanel.BevelBorder = BevelBorder.Right;
            _centerPanel.BevelStyle = BevelStyle.Bumped;

            _stats = new Label(_game.Manager);
            _stats.Text = "";
            _stats.AutoSize = true;
            _stats.Left = 5;
            _stats.Top = 5;
            _stats.Parent = _centerPanel;

            _rightUpPanel = new AdvancedStackPanel(_game.Manager,Orientation.Horizontal);
            _rightUpPanel.Init();
            _rightUpPanel.Text = "Апгрейды для покупки:";
            _rightUpPanel.Left = 710;
            _rightUpPanel.Top = 0;
            _rightUpPanel.Width = 300;
            _rightUpPanel.Parent = _game.MainWindow;
            _rightUpPanel.AutoScroll = true;
            _rightUpPanel.BevelBorder = BevelBorder.All;
            _rightUpPanel.BevelStyle = BevelStyle.Bumped;
            _rightUpPanel.Height = 150;

            Panel _rightDownPanel = new Panel(_game.Manager);
            _rightDownPanel.Init();
            _rightDownPanel.Left = 710;
            _rightDownPanel.Top = 150;
            _rightDownPanel.Width = 300;
            _rightDownPanel.Height = _game.MainWindow.Height - 185;
            _rightDownPanel.Parent = _game.MainWindow;
            _rightDownPanel.AutoScroll = true;
            _rightDownPanel.BevelBorder = BevelBorder.All;
            _rightDownPanel.BevelStyle = BevelStyle.Bumped;

            TabControl tc = new TabControl(_game.Manager);
            tc.Init();
            tc.AddPage("Пряники");
            tc.AddPage("Хранилища");
            tc.AddPage("Разное");
            tc.Width = 296;
            tc.Height = _game.MainWindow.Height - 189;
            tc.Parent = _rightDownPanel;

            Panel rightDownPanel1 = new Panel(_game.Manager);
            rightDownPanel1.Init();
            rightDownPanel1.Left = 0;
            rightDownPanel1.Top = 0;
            rightDownPanel1.Width = 291;
            rightDownPanel1.Height = _game.MainWindow.Height - 316;
            rightDownPanel1.AutoScroll = true;

            Panel rightDownPanel2 = new Panel(_game.Manager);
            rightDownPanel2.Init();
            rightDownPanel2.Left = 0;
            rightDownPanel2.Top = 0;
            rightDownPanel2.Width = 291;
            rightDownPanel2.Height = _game.MainWindow.Height - 316;
            rightDownPanel2.AutoScroll = true;

            Panel rightDownPanel3 = new Panel(_game.Manager);
            rightDownPanel3.Init();
            rightDownPanel3.Left = 0;
            rightDownPanel3.Top = 0;
            rightDownPanel3.Width = 291;
            rightDownPanel3.Height = _game.MainWindow.Height - 316;
            rightDownPanel3.AutoScroll = true;

           

            int top1 = 5;
            int top2 = 5;
            int top3 = 5;
            foreach (KeyValuePair<int, Structure> structure in Structures.List)
            {
                ImageButton btn = new ImageButton(_game.Manager);
                btn.Init();
                btn.Left = 5;
                
                btn.Height = 70;
                btn.Width = 264;
                try
                {
                    btn.Image = (Texture2D)Game1.Resources.GetResource("Images/Game/Structures/structure_" + structure.Key, typeof(Texture2D));
                }
                catch (Exception ex)
                {
                    btn.Image = _flareImg;
                }
                btn.Text = structure.Value.Name + Environment.NewLine + "Стоимость: " + CountStructurePrice(structure.Key);
                btn.Visible = true;
                if (structure.Value.Type == 0)
                {
                    btn.Top = top1;
                    rightDownPanel1.Add(btn);
                    top1 += 75;
                }
                else if (structure.Value.Type == 1)
                {
                    btn.Top = top2;
                    rightDownPanel2.Add(btn);
                    top2 += 75;
                }
                else if (structure.Value.Type == 2)
                {
                    btn.Top = top3;
                    rightDownPanel3.Add(btn);
                    top3 += 75;
                }
                ToolTip tt = new ToolTip(_game.Manager);
                tt.Init();
                btn.ToolTip = tt;
                btn.TextAlignment = Alignment.MiddleLeft;
                btn.ButtonTextMode = ButtonTextMode.Centered;
                btn.Click += new TomShane.Neoforce.Controls.EventHandler(structureBtn_Click);
                btn.Tag = structure.Key;
                
                _structureButtons.Add(btn);
            }
            tc.TabPages[0].Add(rightDownPanel1);
            tc.TabPages[1].Add(rightDownPanel2);
            tc.TabPages[2].Add(rightDownPanel3);
            //RefreshStructureButtons();
            
            TabControl tbc = new TabControl(_game.Manager);
            Console con1 = new Console(_game.Manager);
            Console con2 = new Console(_game.Manager);

            // Setup of TabControl, which will be holding both consoles
            tbc.Init();
            tbc.AddPage("Global");
            tbc.AddPage("Private");

            tbc.Alpha = 220;
            tbc.Left = 220;
            tbc.Top = 500;
            tbc.Height = 260;
            tbc.Width = 495;

            tbc.MinimumHeight = 96;
            tbc.MinimumWidth = 160;

            tbc.TabPages[0].Add(con1);
            tbc.TabPages[1].Add(con2);

            con1.Init();
            con2.Init();

            con2.Width = con1.Width = tbc.TabPages[0].ClientWidth;
            con2.Height = con1.Height = tbc.TabPages[0].ClientHeight;
            con2.Anchor = con1.Anchor = Anchors.All;

            con1.Channels.Add(new ConsoleChannel(0, "General", Color.Orange));
            con1.Channels.Add(new ConsoleChannel(1, "Private", Color.White));
            con1.Channels.Add(new ConsoleChannel(2, "System", Color.Yellow));

            // We want to share channels and message buffer in both consoles
            con2.Channels.Add(new ConsoleChannel(1, "Private", Color.White));
            con2.Channels.Add(new ConsoleChannel(2, "System", Color.Yellow));
            //con2.Channels = con1.Channels;
            ChatBuffer = con2.MessageBuffer = con1.MessageBuffer;

            // In the second console we display only "Private" messages
            con2.ChannelFilter.Add(1);

            // Select default channels for each tab
            con1.SelectedChannel = 0;
            con2.SelectedChannel = 1;

            // Do we want to add timestamp or channel name at the start of every message?
            con1.MessageFormat = ConsoleMessageFormats.All;
            con2.MessageFormat = ConsoleMessageFormats.TimeStamp;

            // Handler for altering incoming message
            con1.MessageSent += new ConsoleMessageEventHandler(_console_MessageSent);
            con2.MessageSent += _console_MessageSent;

            _game.Manager.Add(tbc);

            AdvancedStackPanel sp = new AdvancedStackPanel(_game.Manager, Orientation.Horizontal);
            sp.Top = 170;
            sp.Left = 2;
            sp.Init();
            sp.AutoScroll = true;
            sp.Width = _centerPanel.Width - 4;
            
            foreach (KeyValuePair<int, Achievement> achievement in Achievements.List)
            {
                ImageButton b = new ImageButton(_game.Manager);
                b.Init();
                b.Width = 50;
                b.Height = 50;
                b.Image = achievement.Value.Hidden ?_flareImg : _gingerManImg;
                b.Text = "";
                b.Tag = achievement.Key;
                ToolTip tt = new ToolTip(_game.Manager);
                if(achievement.Value.Hidden)
                    tt.Text = string.Format("{0}" + Environment.NewLine + "{1}", "???", "Неизвестное достижение");
                else
                    tt.Text = string.Format("{0}" + Environment.NewLine + "{1}", achievement.Value.Name, achievement.Value.Description);
                b.ToolTip = tt;
                sp.Add(b);
                _achievementsButtons.Add(b);
                b.Enabled = false;
                //b.Parent = sp;
            }
            sp.Text = "Достижения:";
            sp.Height = 150;
            
            //sp.Parent = _game.MainWindow;
            _centerPanel.Add(sp, false);
            
            sp.BevelBorder = BevelBorder.All;
            sp.BevelStyle = BevelStyle.Bumped;

            _gainedUpgradesPanel = new AdvancedStackPanel(_game.Manager, Orientation.Horizontal);
            _gainedUpgradesPanel.Top = 320;
            _gainedUpgradesPanel.Text = "Купленные улучшения:";
            _gainedUpgradesPanel.Left = 2;
            _gainedUpgradesPanel.Init();
            _gainedUpgradesPanel.AutoScroll = true;
            _gainedUpgradesPanel.Width = _centerPanel.Width - 4;
            _gainedUpgradesPanel.HorizontalScroll = false;

            foreach (int up in _user.Upgrades)
            {
                BoughtUpgrade(up);
            }
            _gainedUpgradesPanel.Height = 150;

            //sp.Parent = _game.MainWindow;
            _centerPanel.Add(_gainedUpgradesPanel, false);

            _gainedUpgradesPanel.BevelBorder = BevelBorder.All;
            _gainedUpgradesPanel.BevelStyle = BevelStyle.Bumped;

            _goldenGinger = new ImageBox(_game.Manager);
            _goldenGinger.Init();
            _goldenGinger.Image = _gingerImgGlow;
            _goldenGinger.Height = 50;
            _goldenGinger.Width = 50;
            _goldenGinger.Color = Color.Gold;
            _goldenGinger.Visible = false;
            _goldenGinger.Click += _goldenGinger_Click;
            //_goldenGinger.Parent = _game.MainWindow;
            _goldenGinger.SizeMode = SizeMode.Stretched;
            _game.Manager.Add(_goldenGinger);

            FightPanel gamePanel = new FightPanel(_game.Manager);
            gamePanel.Background = (Texture2D) Game1.Resources.GetResource("Images/Game/bg", typeof (Texture2D));
            gamePanel.FightingTexture = (Texture2D)Game1.Resources.GetResource("Images/Game/attack1", typeof(Texture2D));
            gamePanel.WalkingTexture = (Texture2D)Game1.Resources.GetResource("Images/Game/run1", typeof(Texture2D));
            gamePanel.DyingTexture = (Texture2D)Game1.Resources.GetResource("Images/Game/die1", typeof(Texture2D));
            gamePanel.StandingTexture = (Texture2D)Game1.Resources.GetResource("Images/Game/stand1", typeof(Texture2D));
            gamePanel.Init();
            gamePanel.Top = _game.MainWindow.ClientTop;
            gamePanel.Left = _game.MainWindow.ClientLeft;
            gamePanel.Height = _game.MainWindow.ClientHeight;
            gamePanel.Width = _game.MainWindow.ClientWidth;

            _game.Manager.Add(gamePanel);

            base.LoadContent(content);
            RefreshStructureButtons();
            

        }

        void b_Click(object sender, EventArgs e)
        {
            int id = (int)((ImageButton) sender).Tag;
            //TODO: network buy
            NetOutgoingMessage om = Game1.Client.CreateMessage();
            om.Write((short)PacketType.Upgrade);
            om.Write(id);
            Game1.Client.SendMessage(om, NetDeliveryMethod.ReliableOrdered);
            ImageButton b = _upgradeButtons.FirstOrDefault(p => ((int) p.Tag) == id);
            b.Dispose();
        }

        void _goldenGinger_Click(object sender, EventArgs e)
        {
            _goldenGinger.Visible = false;
            //_goldenGingerClicked = DateTime.Now;
            NetOutgoingMessage om = Game1.Client.CreateMessage();
            om.Write((short)PacketType.GoldenGinger);
            Game1.Client.SendMessage(om, NetDeliveryMethod.ReliableOrdered);
        }

        void RefreshUpgrades()
        {
            foreach (KeyValuePair<int, Upgrade> upgrade in Upgrades.List)
            {
                bool allConditions = true;

                Upgrade up = upgrade.Value;
                if (_user.Upgrades.Contains(up.Id))//уже купили апгрейд
                {
                    allConditions = false;
                }
                if (_upgradeButtons.FirstOrDefault(p => (int)p.Tag == upgrade.Key) != null)
                {
                    allConditions = false;
                }
                if (up.AchievementsNeed != null)
                {
                    foreach (int id in up.AchievementsNeed)
                    {
                        if (!_user.Achievements.Contains(id))
                        {
                            allConditions = false;
                            break;
                        }
                    }
                }
                if (up.StructuresNeed != null)
                {
                    foreach (KeyValuePair<int, int> s in up.StructuresNeed)
                    {
                        if (!_user.Structures.ContainsKey(s.Key))
                        {
                            allConditions = false;
                            break;
                        }
                        else
                        {
                            if (_user.Structures[s.Key] < s.Value)
                            {
                                allConditions = false;
                                break;
                            }
                        }
                    }
                }
                if (allConditions)//appear button
                {
                    ImageButton b = new ImageButton(_game.Manager);
                    b.Init();
                    b.Width = 50;
                    b.Height = 50;
                    b.Image = _gingerImg;
                    b.Text = "";
                    b.Tag = up.Id;
                    ToolTip tt = new ToolTip(_game.Manager);
                    tt.Text = string.Format("{0}" + Environment.NewLine + "{1}", up.Name, up.Description);
                    b.ToolTip = tt;
                    _rightUpPanel.Add(b);
                    _upgradeButtons.Add(b);
                    b.Enabled = _user.Money >= up.Cost;
                    b.Click += b_Click;
                }
            }


            foreach (ImageButton button in _upgradeButtons)
            {
                int id = (int) button.Tag;
                if (_user.Money >= Upgrades.List[id].Cost)
                {
                    button.Enabled = true;
                }
                else
                {
                    button.Enabled = false;
                }
            }
            foreach (int upgrade in _user.Upgrades)
            {
                if (_gainedUpgradeButtons.FirstOrDefault(p => (int) p.Tag == upgrade) == null)
                {
                    BoughtUpgrade(upgrade);
                }
            }
        }

        void BoughtUpgrade(int id)
        {
            Upgrade up = Upgrades.List[id];
            ImageButton b = new ImageButton(_game.Manager);
            b.Init();
            b.Width = 50;
            b.Height = 50;
            b.Image = _gingerImg;
            b.Text = "";
            b.Tag = up.Id;
            ToolTip tt = new ToolTip(_game.Manager);
            tt.Text = string.Format("{0}" + Environment.NewLine + "{1}", up.Name, up.Description);
            b.ToolTip = tt;
            _gainedUpgradesPanel.Add(b);
            _gainedUpgradeButtons.Add(b);
            b.Enabled = true;
        }

        public void GoldenGingerAppears()
        {
            _goldenGingerAppeared = DateTime.Now;
            _goldenGinger.Top = rnd.Next(_game.MainWindow.ClientRect.Y, _game.MainWindow.ClientRect.Height - _goldenGinger.Height);//Random
            _goldenGinger.Left = rnd.Next(_game.MainWindow.ClientRect.X, _game.MainWindow.ClientRect.Width - _goldenGinger.Width);//Random
            _goldenGinger.Visible = true;
            _goldenGinger.Detached = false;
            _goldenGinger.StayOnTop = true;
            _goldenGinger.BringToFront();
        }


        void _console_MessageSent(object sender, ConsoleMessageEventArgs e)
        {
            //e.Handled = false;
            string message = e.Message.Text;
            NetOutgoingMessage om = Game1.Client.CreateMessage();
            om.Write((short)PacketType.Chat);
            om.Write(e.Message.Channel);
            om.Write(e.Message.Text);
            Game1.Client.SendMessage(om, NetDeliveryMethod.ReliableOrdered);
            e.Handled = true;
            //_console.Tex
            //e.Message.
            //throw new NotImplementedException();
        }

        private decimal CountStructurePrice(int id)
        {
            decimal basePrice = Structures.List[id].BasePrice;
            decimal r = basePrice;
            if (User.Structures != null)
            {
                if (User.Structures.ContainsKey(id))
                {
                    //var price=this.basePrice*Math.pow(Game.priceIncrease,this.amount);
                    double count = User.Structures[id];

                    r = r * (decimal)Math.Pow(1.15d, count);
                }
            }
            return r;
        }

        void RefreshStructureButtons()
        {
            for (int i = 0; i < _structureButtons.Count; i++)
            {
                int id = (int)_structureButtons[i].Tag;
                decimal price = CountStructurePrice(id);
                long count = 0;
                if (User.Structures != null)
                {
                    if (User.Structures.ContainsKey(id))
                    {
                        count = User.Structures[id];
                    }
                }
                _structureButtons[i].Text = Structures.List[id].Name + Environment.NewLine + "Стоимость: " + price.ToString("N0") + Environment.NewLine + "В наличии: " + count;
                _structureButtons[i].ToolTip.Text = string.Format(_structureToolTip, price, Structures.List[id].Income, Structures.List[id].GingerManIncome, Structures.List[id].GlasurIncome, Structures.List[id].AdvancedGingerManIncome, count);
                if (User.Money < CountStructurePrice(id))
                {
                    _structureButtons[i].Enabled = false;
                }
                else
                {
                    _structureButtons[i].Enabled = true;
                }
            }
            RefreshAchievementsButtons();
            RefreshUpgrades();
        }

        void RefreshAchievementsButtons()
        {
            foreach (ImageButton button in _achievementsButtons)
            {
                int id = (int) button.Tag;
                
                if (_user.Achievements.Contains(id))
                {
                    if (Achievements.List[id].Hidden)
                    {
                        button.Image = _gingerManImg;
                        button.ToolTip.Text = string.Format("{0}" + Environment.NewLine + "{1}", Achievements.List[id].Name, Achievements.List[id].Description);
                        //TODO: make right imgs
                    }
                    button.Enabled = true;
                }
                else
                {
                    if (Achievements.List[id].Hidden)
                    {
                        button.ToolTip.Text = string.Format("{0}" + Environment.NewLine + "{1}", "???", "Неизвестное достижение");
                    }
                    button.Enabled = false;
                }
            }
        }
        private void structureBtn_Click(object sender, EventArgs e)
        {
            //throw new NotImplementedException();
            Button btn = (Button)sender;
            int id = (int)btn.Tag;
            decimal price = CountStructurePrice(id);
            long count = 1;
            if (User.Money < price)
            {
                return;
            }
            if (User.Structures == null)
            {
                User.Structures = new Dictionary<int, long>();

            }
            if (User.Structures.ContainsKey(id))
            {
                //var price=this.basePrice*Math.pow(Game.priceIncrease,this.amount);
                User.Structures[id] += 1;
                count = User.Structures[id];
            }
            else
            {
                User.Structures.Add(id, 1);
                //count = 1;
            }
            User.Money -= price;

            NetOutgoingMessage nom = Game1.Client.CreateMessage();
            nom.Write((short)PacketType.BuyStructure);
            nom.Write(id);
            Game1.Client.SendMessage(nom, NetDeliveryMethod.ReliableOrdered);

            RefreshStructureButtons();
        }

        void clickers_MouseOver(object sender, MouseEventArgs e)
        {
            ImageBox ib = (ImageBox)sender;
            if (ib.Color == Color.Black)
                return;

            switch ((int)ib.Tag)
            {
                case 0://пряник
                    ib.Image = _gingerImgGlow;
                    break;
                case 1://пряничный человечек
                    ib.Image = _gingerManImgGlow;
                    break;
                case 2://глазурь
                    ib.Image = _glasurImgGlow;
                    break;
                case 3://улучшенный пряничный человечек
                    ib.Image = _advancedGingerManImgGlow;
                    break;
            }
        }

        void clickers_MouseOut(object sender, MouseEventArgs e)
        {
            ImageBox ib = (ImageBox)sender;
            switch ((int)ib.Tag)
            {
                case 0://пряник
                    ib.Image = _gingerImg;
                    break;
                case 1://пряничный человечек
                    ib.Image = _gingerManImg;
                    break;
                case 2://глазурь
                    ib.Image = _glasurImg;
                    break;
                case 3://улучшенный пряничный человечек
                    ib.Image = _advancedGingerManImg;
                    break;
            }
        }

        public void clickers_MouseDown(object sender, MouseEventArgs e)
        {
            if (e.Button != MouseButton.Left)
                return;
            ImageBox ib = (ImageBox)sender;
            if (ib.Color == Color.Black)
                return;

            ib.Top += 3;
            ib.Left += 3;
            ib.Width = 95;
            ib.Height = 95;
            switch ((int)ib.Tag)
            {
                case 0://нажали на пряник
                    _user.Money += _user.ClickIncome;
                    _gingerclicks++;
                    break;
                case 1://нажали на пряничного человечка
                    if (_user.Money >= 1000)
                    {
                        _user.GingerMan += 1;
                        _user.Money -= 1000;
                        _gingermanclicks++;
                    }
                    break;
                case 2://нажали на глазурь
                    _user.Glasur += _user.GlasurClickIncome;
                    _glasurclicks++;
                    break;
                case 3://нажали на улучшенного пряничного человечка
                    if (_user.GingerMan >= 3 && _user.Glasur >= 1000 && _user.Money >= 10000)
                    {
                        _user.GingerMan -= 3;
                        _user.Glasur -= 1000;
                        _user.Money -= 10000;
                        _user.AdvancedGingerMan += 1;
                        _advgingermanclicks++;
                    }
                    break;
                //TODO: добавить проверки, есть ли такие исследования, что бы можно было создавать человечков и глазурь?
            }
            //ib.Suspended = true;
        }

        public void clickers_MouseUp(object sender, MouseEventArgs e)
        {
            if (e.Button != MouseButton.Left)
                return;
            ImageBox ib = (ImageBox)sender;
            if (ib.Color == Color.Black)
                return;
            ib.Top -= 3;
            ib.Left -= 3;
            ib.Width = 100;
            ib.Height = 100;

        }

        public override void ShowMessage(string errorMessage, string title, MessageType type)
        {
            switch (type)
            {
                case MessageType.General:
                case MessageType.Warning:
                    ShowMessage(errorMessage, title, type, new TomShane.Neoforce.Controls.EventHandler(btn_Click), null);
                    break;
                case MessageType.Question:
                    break;
                case MessageType.Error:
                    ShowMessage(errorMessage, "Ошибка", MessageType.Error, new TomShane.Neoforce.Controls.EventHandler(btnYesConnectError_Click), null);
                    break;
            }
        }

        public void ShowMessage(string message, string title, MessageType type, TomShane.Neoforce.Controls.EventHandler okBtnClick, TomShane.Neoforce.Controls.EventHandler noBtnClick)
        {
            Window msg = new Window(_game.Manager);

            TextBox tb = new TextBox(_game.Manager);
            ImageBox img = new ImageBox(_game.Manager);
            msg.Init();

            tb.Init();
            img.Init();
            switch (type)
            {
                case MessageType.General:
                case MessageType.Warning:
                case MessageType.Error:
                    Button btn = new Button(_game.Manager);
                    btn.Init();
                    btn.SetPosition(150, 130);
                    btn.Text = "OK";
                    btn.Height = 20;
                    btn.Width = 100;
                    btn.Parent = msg;
                    btn.Click += okBtnClick;//new TomShane.Neoforce.Controls.EventHandler(btn_Click);
                    break;
                case MessageType.Question:
                    Button btnYes = new Button(_game.Manager);
                    Button btnNo = new Button(_game.Manager);
                    btnYes.Init();
                    btnNo.Init();
                    btnYes.SetPosition(96, 130);
                    btnYes.Text = "Да";
                    btnYes.Height = 20;
                    btnYes.Width = 100;
                    btnYes.Parent = msg;
                    btnYes.Click += okBtnClick;//new TomShane.Neoforce.Controls.EventHandler(btnYes_Click);

                    btnNo.SetPosition(204, 130);
                    btnNo.Text = "Нет";
                    btnNo.Height = 20;
                    btnNo.Width = 100;
                    btnNo.Parent = msg;
                    btnNo.Click += noBtnClick;//new TomShane.Neoforce.Controls.EventHandler(btn_Click);
                    break;
            }


            msg.Width = 400;
            msg.Height = 200;
            msg.Parent = _game.MainWindow;
            msg.Text = title;
            msg.Resizable = false;
            msg.CloseButtonVisible = false;
            msg.Movable = false;
            msg.StayOnTop = true;
            msg.Center();

            //msg.Top = int.MaxValue;

            img.Image = _msgImgs[type];
            img.Parent = msg;
            img.SetPosition(10, 10);

            tb.SetPosition(70, 10);
            tb.Width = 300;
            tb.Height = 120;
            //tb.Mode = TextBoxMode.Multiline;
            tb.WordWrapping = true;
            tb.Text = message;
            tb.Parent = msg;
            tb.DrawBorders = false;
            tb.ReadOnly = true;
            tb.CanFocus = false;
            tb.TextColor = Color.Red;
            //tb.Init();



            msg.ShowModal();
            //msg.Show();
            _game.Manager.Add(msg);
        }

        void btnYes_Click(object sender, TomShane.Neoforce.Controls.EventArgs e)
        {
            //DeleteChar();
            Button btn = (Button)sender;
            Window wnd = (Window)((ClipBox)btn.Parent).Parent;
            wnd.Close();
        }

        void btn_Click(object sender, TomShane.Neoforce.Controls.EventArgs e)
        {
            Button btn = (Button)sender;
            Window wnd = (Window)((ClipBox)btn.Parent).Parent;
            wnd.Close();
            //throw new NotImplementedException();
        }

        void btnYesConnectError_Click(object sender, TomShane.Neoforce.Controls.EventArgs e)//вызывается если показалось окно с проблемой соединения, закрывает игру
        {
            //DeleteChar();
            Button btn = (Button)sender;
            Window wnd = (Window)((ClipBox)btn.Parent).Parent;
            wnd.Close();
            _game.Exit();
        }

        public override void Dispose()
        {
            base.Dispose();
        }
    }
}
